package com.hexinfo.dmpro.common.utils;

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.Map;

/**
 * yemw
 * 读取集群热备配置文件
 */
public class ReadYmlUtil {

    /**
     * 读取yml文件为map
     * @param path 路径
     * @return
     */
    public Map<Object,Object> readYml(String path){
        try {
            Yaml yaml = new Yaml();
            URL url = new URL(path);
            if (url != null) {
                //获取test.yaml文件中的配置数据，然后转换为obj，
//                Object obj =yaml.load(new FileInputStream(url.getFile()));
//                System.out.println(obj);
                //也可以将值转换为Map
                Map map =(Map)yaml.load(new FileInputStream(url.getFile()));
//                System.out.println("标识符===========================");
                //通过map我们取值就可以了.
            return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成yml
     * @param path 文件全路径
     * @param content 内容
     */
    public void generateYml(String path,String content){
        Yaml yml = new Yaml();
        // 判断文件夹是否存在
        if (FileUtil.exist(path)) {
            File file = new File(path);
            //内容写入
            try (FileWriter writer = new FileWriter(file)) {
                //writer.write(yml.dump(obj));
//                writer.write(yml.dumpAsMap(obj));
//                writer.write(yml.dumpAs(obj, Tag.MAP, DumperOptions.FlowStyle.BLOCK));
                //可以自定义写入格式
                //writer.write(yml.dumpAs(obj, Tag.MAP, DumperOptions.FlowStyle.FLOW));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            //创建yml
            File file = FileUtil.touch(path);
        }
    }
}
